package practice.library.slick

import java.util.concurrent.TimeUnit

import miduoduodb.basic.Tables._
import slick.backend.DatabaseConfig
import slick.lifted.TableQuery
import slick.driver.MySQLDriver.api._

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext}

/**
  * Created by lovepocky(lovepocky@foxmail.com) on 2016/4/3.
  */
object SlickPractice {
	val db = slick.jdbc.JdbcBackend.Database.forConfig("mysql")
	implicit val ec = ExecutionContext.global
	
	def main(args: Array[String]) {
		initJobs()
		
		//Start
		val selectItems = TableQuery[Selectitem]
		val wxfaninfos = TableQuery[Wxfaninfo]
		val wxfanpayrecords = TableQuery[Wxfanpayrecord]
		val goodsrecordtotal = TableQuery[Goodsrecordtotal]
		
		val startAction = DBIO.seq()
		val startFuture = db.run(startAction
		).flatMap { _ =>
			//filter(where)
			val queryAction = selectItems.filter(_.`type` === 1.toShort)
			println(queryAction.result.statements)
			db.run(queryAction.result.map(println))
		}.flatMap { _ =>
			//inner join(actually where)
			val action = wxfaninfos.filter(_.fanid === 6L)
					.flatMap(it => wxfanpayrecords.map((_, it)))
					.filter(it => it._1.fanopenid === it._2.fanopenid)
			println(action.result.statements)
			db.run(action.result.map(println))
		}.flatMap { _ =>
			//inner join(actually where)(more flexible than above)
			val action = for (
				wxfaninfo <- wxfaninfos if wxfaninfo.fanid === 6L;
				wxfanpayrecord <- wxfanpayrecords if wxfaninfo.fanopenid === wxfanpayrecord.fanopenid
			) yield (wxfaninfo.fanid, wxfanpayrecord)
			println(action.result.statements)
			db.run(action.result.map(_.foreach(println)))
		}.flatMap { _ =>
			//todo leftJoin
			val action = for (
				wxfaninfo <- wxfaninfos if wxfaninfo.fanid === 6L;
				wxfanpayrecord <- wxfanpayrecords if wxfaninfo.fanopenid === wxfanpayrecord.fanopenid
			) yield (wxfaninfo.fanid, wxfanpayrecord)
			println(action.result.statements)
			db.run(action.result.map(_.foreach(println)))
		}.flatMap { _ =>
			//self set
			val action = goodsrecordtotal.filter(_.goodsid === 8L)
			println(action.result.statements)
			db.run(action.result.map(_.foreach(println)))
		}
		Await.result(startFuture, Duration.Inf)
		
		val anotherAction = DBIO.seq()
		val anotherFuture = db.run(anotherAction)
		Await.result(anotherFuture, Duration.Inf)
	}
	
	def initJobs() = {
		
	}
}
